package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/8 13:26
 */
public class PlatesBetweenCandles {


    public static void main(String[] args) {
        PlatesBetweenCandles test = new PlatesBetweenCandles();

        // [2,3]
        String str = "**|**|***|";
        int[][] arr = {{2, 5}, {5, 9}};

        // [9,0,0,0,0]
//        String str = "***|**|*****|**||**|*";
//        int[][] arr = {{1, 17}, {4, 5}, {14, 17}, {5, 11}, {15, 16}};

        int[] ints = test.platesBetweenCandles(str, arr);
        System.out.println(Arrays.toString(ints));
    }

    public int[] platesBetweenCandles(String s, int[][] queries) {
        char[] chars = s.toCharArray();
        int length = s.length();
        int[] arr1 = new int[length];
        int[] arr2 = new int[length];
        int count = 0;
        int item = -1;
        for (int i = 0; i < length; i++) {
            char c = chars[i];
            if (c == '*') {
                count++;
                arr1[i] = item;
            } else {
                item = i;
                arr1[i] = count;
            }
        }
        item = -1;
        for (int i = length - 1; i >= 0; i--) {
            if (chars[i] == '*') {
                arr2[i] = item;
            } else {
                item = i;
            }
        }
        int l = queries.length;
        int[] values = new int[l];
        for (int i = 0; i < l; i++) {
            int a = queries[i][0];
            int b = queries[i][1];
            int st = arr1[a];
            if (chars[a] == '*') {
                if (arr2[a] < 0) {
                    values[i] = 0;
                    continue;
                }
                st = arr1[arr2[a]];
            }
            int end = arr1[b];
            if (chars[b] == '*') {
                if (arr1[b] < 0) {
                    values[i] = 0;
                    continue;
                }
                end = arr1[arr1[b]];
            }
            values[i] = end - st > 0 ? end - st : 0;
        }
        return values;
    }

}
